import React, {Component} from 'react'
import {connect} from 'react-redux'
import Slider, {Range} from 'rc-slider'
import {formatDiff, ReplayVideoPlayer, originData, EventCenter} from '@utils/Global'
import {FOOTER_SHOW_TIME} from '@utils/config'
import PlayController from '@utils/PlayController'
import ReplayPlayer from '@utils/ReplayPlayer'
import {ReplayAction} from '@act'

const {updateFooter, toggleShowType, changeSwiperIndex} = ReplayAction

class ReplayFooter extends Component {
  footerShowTimer = null
  isSliding = false
  sliderDotsBindEvent = false
  state = {
    sliderValue: 0,
    currentMark: null
  }

  stopFooterTimer() {
    this.footerShowTimer && clearTimeout(this.footerShowTimer)
  }

  startFooterTimer() {
    const {dispatch} = this.props
    this.stopFooterTimer()
    this.footerShowTimer = setTimeout(() => {
      dispatch(toggleShowType('footer', false))
    }, FOOTER_SHOW_TIME)
  }

  handleClickSwiper = () => {
    const {dispatch, isPause} = this.props
    dispatch(toggleShowType('footer', true))
    if (isPause) {
      return
    }
    this.startFooterTimer()
  }
  updateTime = (t) => {
    if (this.isSliding) {
      return
    }
    const {fullTime, dispatch} = this.props
    dispatch(updateFooter('currentTime', t * 1000))
    var percent = (t * 1000) / fullTime
    this.setState({
      sliderValue: percent * 10000
    })
  }

  sliderChange(val) {
    const {fullTime, dispatch} = this.props
    this.setState({
      sliderValue: val
    })
    var percent = val / 10000
    var currentTime = Math.floor(percent * fullTime)
    dispatch(updateFooter('currentTime', currentTime))
  }

  onBeforeChange() {
    const {dispatch} = this.props
    this.isSliding = true
    dispatch(toggleShowType('footer', true))
    this.stopFooterTimer()
  }

  afterSliderChange(val) {
    this.startFooterTimer()
    this.isSliding = false
    const {dispatch} = this.props
    dispatch(updateFooter('isPause', false))
    var p = val / 10000
    PlayController.stop()
    PlayController.initProgress(p, (obj) => {
      console.log('obj', obj)
      const data = originData['replay']
      var task = obj.lastTask
      if (obj.realType === 'go_to') {
        var index = obj.type === 'first' ? 0 : parseInt(obj.lastTask.data.index)
        console.log('goto', index)
        dispatch(changeSwiperIndex(index))
      }
      dispatch(toggleShowType('mediaLoading', true))
      var seekTime = parseInt(obj.realAudioTime / 1000)
      if (obj.realAudioTime >= originData['replay'].audio.duration * 1000) {
        seekTime = parseInt(originData['replay'].audio.duration) - 1
      }
      ReplayPlayer.seekTo(seekTime, () => {
        dispatch(toggleShowType('mediaLoading', false))
        if (obj.playVideo) {
          ReplayPlayer.pause()
          dispatch(toggleShowType('videoMask', true))
          ReplayVideoPlayer.play(obj.lastTask.data.url, obj.realVideoTime / 1000, () => {

          }, () => {
            dispatch(toggleShowType('videoMask', false))
            obj.lastTask.done = true
            obj.playVideoCallback && obj.playVideoCallback()
            ReplayPlayer.start()
            PlayController.start()
          })
        } else {
          dispatch(toggleShowType('videoMask', false))
          ReplayPlayer.start()
          PlayController.start()
        }
      })
    })
  }

  clickAction = () => {
    const {isPause, dispatch} = this.props
    if (isPause) {
      ReplayPlayer.start()
      PlayController.start()
      dispatch(updateFooter('isPause', false))
      this.startFooterTimer()
    } else {
      ReplayPlayer.pause()
      PlayController.stop()
      dispatch(updateFooter('isPause', true))
      dispatch(toggleShowType('footer', true))
      this.stopFooterTimer()
    }
  }

  componentDidMount() {
    PlayController.setUpdateTimeCallback(this.updateTime)
    EventCenter.addListener('click_swiper', this.handleClickSwiper)
  }
  addMarkHovorEvent() {
    let dots = document.querySelectorAll('.rc-slider-dot')
    if (this.sliderDotsBindEvent || dots.length <= 0) {
      return
    }
    Array(dots.length).fill(0).map((z, index) => {
      let ele = dots[index]
      ele.addEventListener('mouseover', () => {
        this.onMarkMouseInCallback(index)
      }, false)
      ele.addEventListener('mouseout', () => {
        this.onMarkMouseOutCallback(index)
      }, false)
    })
    this.sliderDotsBindEvent = true
  }
  componentDidUpdate() {
    this.addMarkHovorEvent()
  }
  onMarkMouseInCallback(mIndex) {
    const { marks } = this.props
    this.setState({currentMark: marks[mIndex]})
  }
  onMarkMouseOutCallback(mIndex) {
    this.setState({currentMark: null})
  }
  renderMarkTag() {
    if (!this.state.currentMark) {
      return null
    }
    const {marks} = this.props
    let index = marks.findIndex(_ => JSON.stringify(_) === JSON.stringify(this.state.currentMark))
    let dots = document.querySelectorAll('.rc-slider-dot')
    let left = dots[index].offsetLeft || 0
    let style = {
      left: `${180 + left + 3}px`
    }
    return (
      <div className="footer_mark" style={style}>
        {`${this.state.currentMark.time} ${this.state.currentMark.title}`}
      </div>
    )
  }
  componentWillUnmount() {
    EventCenter.removeListener('click_swiper', this.handleClickSwiper)
  }
  formatMarks() {
    const {marks, fullTime} = this.props
    if (fullTime <= 0) {
      return {}
    }
    let m = {}
    marks.map(_ => {
      let p = Math.floor(_.diff * 1000 / fullTime * 10000)
      m[p] = ''
      return null
    })
    return m
  }
  render() {
    const {currentTime, fullTime, isPause, show} = this.props
    const slider_props = {
      className: 'footer_slider',
      min: 0,
      max: 10000,
      step: 1,
      defaultValue: 0,
      value: this.state.sliderValue,
      dotStyle: {
        width: '6px',
        height: '6px',
        borderRadius: '50%',
        border: 'none'
      },
      railStyle: {
        height: '6px',
        backgroundColor: 'rgba(255,255,255, .2)'
      },
      trackStyle: {
        height: '6px',
        backgroundColor: 'red'
      },
      handleStyle: {
        backgroundColor: 'red',
        border: 'none'
      },
      marks: this.formatMarks()
    }
    const footerClass = show ? 'replay_footer show' : 'replay_footer hide'
    const actionClassName = isPause ? 'footer_action play' : 'footer_action pause'
    return (
      <div className={footerClass}>
        {this.renderMarkTag()}
        <div className={actionClassName} onClick={this.clickAction}></div>
        <div className="footer_time left">{formatDiff(currentTime)}</div>
        <div className="footer_progress">
          <Slider
            {...slider_props}
            onChange={this.sliderChange.bind(this)}
            onAfterChange={this.afterSliderChange.bind(this)}
            onBeforeChange={this.onBeforeChange.bind(this)}
          />
        </div>
        <div className="footer_time right">{formatDiff(fullTime)}</div>
      </div>
    )
  }
}

const mapState = (state) => {
  return {
    show: state.ReplayState.showType.footer,
    ...state.ReplayState.footer,
    marks: state.ReplayState.marks
  }
}

export default connect(mapState)(ReplayFooter)
